const Shape = require("./shape.js")
const Utils = require("./utils.js")
const {EN} = require("./constant.js")
module.exports = class Curve extends Shape{
	constructor($env,$event){
		super($env,$event)
		
		this.__relativePlugins=[{name:"LinePicker"}]
		this.transcation = 0
		this.__isInPath = false
		this.bind();
	}
	bind(){
		this.baseContext.canvas.addEventListener("mousedown",(e)=>{
			if (!this.isActive) return;
			var pos = {
					x : e.pageX,
			        y : e.pageY
			}
			
			this.drawStart(this.cvsEvtPos(pos,this.cvs))
			
		})
		this.baseContext.canvas.addEventListener("mousemove",(e)=>{
			if (!this.isActive) return;
			if(this.transcation!==1)return;
			var pos = {
					x : e.pageX,
			        y : e.pageY
			}
			this.drawMove(this.cvsEvtPos(pos,this.cvs))
		})
		this.baseContext.canvas.addEventListener("mouseup",(e)=>{
			if (!this.isActive) return;
			if(this.transcation!==1)return;
			var pos = {
					x : e.pageX,
			        y : e.pageY
			}
			
			this.drawEnd(this.cvsEvtPos(pos,this.cvs))
		})
	}
	rePaint(step,context){
		let ctx = context||this.ctx;
		let fp = step[0];
		ctx.save()
		ctx.lineWidth = 1;
		ctx.strokeStyle = fp.strokeStyle
		ctx.setLineDash(fp.lineDash)

		ctx.beginPath();
		ctx.moveTo(fp.x,fp.y);
		step.forEach((p,i)=>{	
			ctx.lineTo(p.x,p.y);
			ctx.stroke()
		})
		ctx.closePath()
		ctx.restore()
		
	}
	drawEnd(pos){
		this.ctx.closePath();
		this.ctx.restore()
		this.transcation=0;
		this.__steps.push(pos)
		this.emit(EN.update_state,this,this.__steps)
	}
	drawMove(pos){
		let ctx = this.ctx;
		ctx.lineTo(pos.x,pos.y)
		ctx.stroke()
		this.__steps.push(pos)
	}
	drawStart(pos){
		let p = Utils.assign(this.__setting,pos);

		let ctx = this.ctx;
		ctx.save()
		ctx.lineWidth = 1;
		ctx.beginPath()
		ctx.moveTo(p.x,p.y)

		this.transcation = 1;
		p.strokeStyle = ctx.strokeStyle
		p.fillStyle = ctx.fillStyle
		p.lineDash = ctx.getLineDash()
		this.__steps=[p];
	}
}
